<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class GenerateMd5ForSingleTopics extends Command
{
    protected $signature = 'generate:md5-single-topics';
    protected $description = 'Generate MD5 hash for content and associated options in single_topics and update md5code field';

    public function handle()
    {
        $this->info('Starting to process single_topics...');

        $batchSize = 1000; // 每次处理的记录数量
        $offset = 0;

        while (true) {
            DB::beginTransaction();

            try {
                // 获取一批数据
                $topics = DB::connection('test')->table('single_topics')
                            ->select('id', 'content')
                            ->whereNull('md5code')
                            ->offset($offset)
                            ->limit($batchSize)
                            ->get();

                // 如果没有更多数据，则退出循环
                if ($topics->isEmpty()) {
                    DB::commit();
                    break;
                }

                foreach ($topics as $topic) {
                    // 获取与single_topic_id关联的所有title，按id正序拼接
                    $options = DB::connection('test')->table('single_topic_option')
                                 ->where('single_topic_id', $topic->id)
                                 ->orderBy('id')
                                 ->pluck('title')
                                 ->implode(''); // 将所有title拼接成一个字符串
                    // 将content和options拼接，并生成MD5值
                    $md5code = md5($topic->content . $options);

                    // 更新MD5码
                    DB::connection('test')->table('single_topics')
                      ->where('id', $topic->id)
                      ->update(['md5code' => $md5code]);
                }

                DB::commit();

                $offset += $batchSize;
                $this->info("Processed {$offset} records...");

            } catch (\Exception $e) {
                DB::rollBack();
                $this->error("Failed to process batch starting from offset {$offset}: " . $e->getMessage());
                break;
            }
        }

        $this->info('Finished processing single_topics.');
    }
}
